package com.hys.ultrasound.business.login;

import android.text.TextUtils;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.SPUtils;
import com.hys.ultrasound.base.mvp.BasePresenter;
import com.hys.ultrasound.data.entity.AppVersion;
import com.hys.ultrasound.data.entity.UserInfo;
import com.lpjeremy.libmodule.http.callback.HttpRequestCallBack;
import com.lpjeremy.libmodule.http.exception.ApiException;

public class LoginPresenter extends BasePresenter<LoginView> {
    private LoginModel loginModel;

    public LoginPresenter() {
        loginModel = new LoginModel();
    }

    /**
     * 登录
     *
     * @param userName
     * @param passwrod
     */
    public void login(final String userName, final String passwrod) {
        if (!isViewAttached()) {
            mView.noAttachedView();
            return;
        }
        if (TextUtils.isEmpty(userName)) {
            mView.showCheckToast("请输入登录账号");
            return;
        }
        if (TextUtils.isEmpty(passwrod)) {
            mView.showCheckToast("请输入登录密码");
            return;
        }

        mView.showLoading("登录中...");
        loginModel.login(userName, passwrod, new HttpRequestCallBack<UserInfo>() {
            @Override
            public void onSuccess(UserInfo result) {
                if (result.getToken() != null) {
                    SPUtils.getInstance().put("token", result.getToken().getAccess_token());
                    SPUtils.getInstance().put("refreshToken",result.getToken().getRefresh_token());
                    SPUtils.getInstance().put("scanUserName", userName);
                    SPUtils.getInstance().put("scanUserPwd", passwrod);
                }
                if (isViewAttached()) {
                    mView.hideLoading();
                    mView.onLoginSuccess(result);
                }
            }

            @Override
            public void onFail(ApiException e) {
                if (isViewAttached()) {
                    mView.hideLoading();
                    mView.onLoginFail(e);
                }
            }
        });

    }

    /**
     * 检测升级
     */
    public void checkAppVersion() {
        mView.showLoading("初始化中...");
        loginModel.checkAppVersion(String.valueOf(AppUtils.getAppVersionCode()), new HttpRequestCallBack<AppVersion>() {
            @Override
            public void onSuccess(AppVersion appVersion) {
                if (isViewAttached()) {
                    mView.hideLoading();
                    mView.checkAppVersionSuccess(appVersion);
                }
            }

            @Override
            public void onFail(ApiException e) {
                if (isViewAttached()) {
                    mView.hideLoading();
                    mView.checkAppVersionFail(e);
                }
            }
        });
    }

}
